package servlets;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;

import structures.Result;
import twitter4j.internal.org.json.JSONObject;
import managers.JSonManager;

public class GetIntroServlet extends HttpServlet {
	private static final String URLBASE = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts&redirects&format=json&exintro=1&titles=";

	private static final long serialVersionUID = 3530363047001110334L;
	
	//method to read
	protected void doGet(HttpServletRequest request, HttpServletResponse response){
		String requestItem, jsonResult, wikiAnswer, pageNumber, string;
		JSonManager jSonManager;
		JSONObject answerJson;
		Result result;
		URL url;
		jSonManager = new JSonManager();
		requestItem = request.getParameter("requestItem");
		
		try{
			url = new URL(URLBASE + requestItem);
			wikiAnswer = Jsoup.connect(url.toString()).ignoreContentType(true).execute().body();
			answerJson = new JSONObject(wikiAnswer);
			answerJson = answerJson.getJSONObject("query");
			answerJson = answerJson.getJSONObject("pages");
			string = answerJson.toString();
			pageNumber = string.substring(string.indexOf("\"")+1, string.indexOf("\"",4));
			answerJson = answerJson.getJSONObject(pageNumber);
			string = answerJson.getString("extract");
			result = new Result("no", string);
			jsonResult = jSonManager.generateJSON(result);
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			//write the result as JSon
			response.getWriter().write(jsonResult);
		} catch (Exception e) {
			result = new Result("yes", "");
			jsonResult = jSonManager.generateJSON(result);
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			//write the result as JSon
			try {
				response.getWriter().write(jsonResult);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

}
